package com.tungse.study.dynamic_proxy;

import javax.tools.*;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * @author Tungse
 */
public class JavaFileCompiler {

    public static void compiler(File sourceFilePath) {
        // 创建编译器实例
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            System.err.println("找不到Java编译器，请确保已安装JDK并配置环境变量");
            System.exit(1);
        }
        try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {

            Iterable<? extends JavaFileObject> javaFileObjectsFromFiles
                    = fileManager.getJavaFileObjectsFromFiles(List.of(sourceFilePath));

            // 可选参数：编码设置
            List<String> options = Arrays.asList("-d", "./mini_thread\\target\\classes");

            // 创建诊断收集器
            DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();

            // 获取编译任务
            JavaCompiler.CompilationTask task = compiler.getTask(
                    null,
                    fileManager,
                    null,
                    options,
                    null,
                    javaFileObjectsFromFiles
            );

            // 设置输出目录
//        task.setClasspath(outputDir.toURI());
//        task.setDestinationDirectory(outputDir);

            // 执行编译
            boolean success = task.call();
            if (success) {
                System.out.println("编译成功！");
            } else {
                System.err.println("编译失败！");
            }
        } catch (Exception ignored) {

        }
    }
}